import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Tabs, Icon } from 'antd'
import { withI18n, Trans } from '@lingui/react'
import { router } from 'utils'
import { stringify } from 'qs'
import Current from './components/Current'
import History from './components/History'
import ResolvedHistory from './components/ResolvedHistory'
import Header from './components/Header'
import Details from './components/Details'
import Timeline from './components/Timeline'
import DataForm from './components/DataForm'
import Relations from './components/Relations'

const TabPane = Tabs.TabPane
let issubing = false
@withI18n()
@connect(({ userDetail, loading }) => ({ userDetail, loading }))
class UserDetail extends PureComponent {
  componentWillReceiveProps(nextprops) {
    const { userDetail, dispatch } = nextprops
    const { deviceid, SubReport } = userDetail
    if (SubReport || issubing) return
    if (deviceid) {
      console.log('UserDetail will call subUpload')
      // window.onbeforeunload = () => {
      //   dispatch({ type: "userDetail/unsubUpload", payload: { Imei } });
      // }
      issubing = true
      dispatch({ type: 'userDetail/subUpload', payload: { deviceid } }).then(
        () => {
          issubing = false
        }
      )
    }
  }

  componentWillUnmount() {
    const { userDetail, dispatch } = this.props
    const { deviceid } = userDetail

    console.log('UserDetail unmount')

    dispatch({ type: 'userDetail/unsubUpload', payload: { deviceid } })

    dispatch({
      type: `userDetail/back`,
    })
  }

  render() {
    const { userDetail, dispatch, loading, location } = this.props //i18n,
    const {
      data,
      deviceid,
      pathquery,
      laterdata,
      rslaterdata,
      realtime,
      historys,
      dataform,
      relations,
      //
      hisstartdate,
      hisenddate,
      //
      resstartdate,
      resenddate,
      //
      dtfstartdate,
      dtfenddate,

      EditingGeo,
      AllChildGeo,
    } = userDetail
    const Imei = data && data.IMEI && data.IMEI.value
    const query = () => {
      dispatch({ type: 'userDetail/query', payload: { deviceid } })
    }
    const getRelations = () => {
      dispatch({
        type: 'userDetail/getRelations',
        payload: { Imei },
      })
    }
    const refreshdataform = () => {
      dispatch({
        type: 'userDetail/refreshdataform',
        payload: { Imei, dtfstartdate, dtfenddate },
      })
    }
    const getdataform = (dtfstartdate, dtfenddate) => {
      dispatch({
        type: 'userDetail/refreshdataform',
        payload: { Imei, dtfstartdate, dtfenddate },
      })
    }
    const refreshhistory = () => {
      dispatch({ type: 'userDetail/refreshhistory', payload: { deviceid } })
    }
    const gethistorydata = (hisstartdate, hisenddate) => {
      dispatch({
        type: 'userDetail/gethistorydata',
        payload: { Imei, hisstartdate, hisenddate },
      })
    }
    const updateHistoryDate = (hisstartdate, hisenddate) => {
      dispatch({
        type: 'userDetail/updateState',
        payload: { hisstartdate, hisenddate },
      })
    }
    const historyloadmore = () => {
      dispatch({
        type: 'userDetail/devicehistory',
      })
    }
    const moreloading = loading.effects[`userDetail/devicehistory`]
    const setlightloading = loading.effects[`devices/Set_Light`]
    const onSetLight = (Degree, Duration) => {
      dispatch({
        type: `devices/Set_Light`,
        payload: {
          Imei,
          Degree,
          Duration,
        },
      })
    }
    const onSetMode = Mode => {
      dispatch({
        type: `devices/setMode`,
        payload: {
          Imei,
          Mode,
        },
      }).then(() => {
        refreshhistory()
        query()
      })
    }
    const onedit = (type, payload) => {
      dispatch({
        type: `userDetail/${type}`,
        payload: payload,
      }).then(() => {
        refreshhistory()
        query()
      })
    }
    const onback = () => {
      router.push({
        pathname: `/devices`,
        search: stringify(pathquery, { arrayFormat: 'repeat' }),
      })
    }
    const getrealtimedata = () => {
      dispatch({
        type: 'userDetail/getrealtimedata',
        payload: { Imei },
      })
    }
    const updaterealtimedata = realtime => {
      dispatch({ type: 'userDetail/updaterealtimedata', payload: realtime })
    }
    //
    const getresolveddata = (resstartdate, resenddate) => {
      dispatch({
        type: 'userDetail/getresolveddata',
        payload: { Imei, resstartdate, resenddate },
      })
    }
    const updateResolvedDate = (resstartdate, resenddate) => {
      dispatch({
        type: 'userDetail/updateState',
        payload: { resstartdate, resenddate },
      })
    }

    const detailprops = {
      onedit,
    }
    const currentprops = {
      data,
      deviceid,
      Imei,
      getrealtimedata,
      updaterealtimedata,
      SetonReceiveReport: onReceiveReport => {
        dispatch({
          type: 'userDetail/updateState',
          payload: { onReceiveReport },
        })
      },
      realtime: realtime ? realtime : [],
      loading: loading.effects[`userDetail/getrealtimedata`],
    }
    const dataformprops = {
      data,
      deviceid,
      Imei,
      getdataform,
      dtfstartdate,
      dtfenddate,
      updateHistoryDate,
      dataform: dataform ? dataform : [],
      loading: loading.effects[`userDetail/refreshdataform`],
      exportExcel: () => {
        dispatch({
          type: 'userDetail/exportExcel',
          payload: {
            Imei,
            startdate: dtfstartdate,
            enddate: dtfenddate,
          },
        })
      },
    }

    const historyprops = {
      data,
      deviceid,
      Imei,
      gethistorydata,
      hisstartdate,
      hisenddate,
      updateHistoryDate,
      laterdata: laterdata ? laterdata : [],
      loading: loading.effects[`userDetail/gethistorydata`],
    }
    const resolvedprops = {
      data,
      deviceid,
      Imei,
      resstartdate,
      resenddate,
      getresolveddata,
      updateResolvedDate,
      rslaterdata: rslaterdata ? rslaterdata : [],
      loading: loading.effects[`userDetail/getresolveddata`],
    }
    const timelineprops = {
      data,
      refreshhistory,
      historys: historys ? historys : [],
      historyloadmore,
      moreloading,
      location,
    }
    const relationprops = {
      data,
      deviceid,
      Imei,
      relations: relations ? relations : [],
      getRelations,
      loading: loading.effects[`userDetail/getRelations`],
    }
    return (
      <Header
        {...{
          deviceid,
          data,
          refreshhistory,
          onedit,
          onback,
          setlightloading,
          onSetLight,
          onSetMode,
        }}
        footer={
          <Tabs
            defaultActiveKey="1"
            onChange={key => {
              if (key == '2' && dataform == undefined) {
                refreshdataform()
              }
              if (key == '3' && laterdata == undefined) {
                gethistorydata()
              }
              if (key == '4' && realtime == undefined) {
                getrealtimedata()
              }
              if (key == '5' && rslaterdata == undefined) {
                getresolveddata()
              }
              //
              if (key == '6' && relations == undefined) {
                getRelations()
              }
              if (key == '7' && historys == undefined) {
                refreshhistory()
              }
            }}
          >
            <TabPane
              tab={
                <span>
                  <Icon type="code" />
                  <Trans>Device Detail</Trans>
                </span>
              }
              key="1"
            >
              <Details {...detailprops} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <Icon type="read" />
                  <Trans>Data Form</Trans>
                </span>
              }
              key="2"
            >
              <DataForm {...dataformprops} />
            </TabPane>

            <TabPane
              tab={
                <span>
                  <Icon type="area-chart" />
                  <Trans>Historical Data</Trans>
                </span>
              }
              key="3"
            >
              <History {...historyprops} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <Icon type="stock" />
                  <Trans>Real-time Data</Trans>
                </span>
              }
              key="4"
            >
              <Current {...currentprops} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <Icon type="pie-chart" />
                  <Trans>Data Analysis</Trans>
                </span>
              }
              key="5"
            >
              <ResolvedHistory {...resolvedprops} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <Icon type="apartment" />
                  <Trans>Relational map</Trans>
                </span>
              }
              key="6"
            >
              <Relations {...relationprops} />
            </TabPane>
            <TabPane
              tab={
                <span>
                  <Icon type="sliders" />
                  <Trans>Operation history</Trans>
                </span>
              }
              key="7"
            >
              <Timeline {...timelineprops} />
            </TabPane>
          </Tabs>
        }
      />
    )
  }
}
UserDetail.propTypes = {
  userDetail: PropTypes.object,
}

export default UserDetail
